package test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * 第二章示例1
 */
public class XMLParse {
    Document doc=null;
    public void getDocument(){
        //获取解析器工厂
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        //获取解析器
        try {
            DocumentBuilder builder=factory.newDocumentBuilder();
            //加载DOM
            doc=builder.parse("src/main/java/com.bdqn/dom/brande.xml");
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 显示XML中所有信息
     */
    public void showInfo(){
        //获取<Brand>的所有节点集合
        NodeList nodeList=doc.getElementsByTagName("Brand");
        for (int i = 0; i < nodeList.getLength(); i++){
            Node brand=nodeList.item(i);
            Element brandEle=(Element) brand;
            String brandStr=brandEle.getAttribute("name");
            NodeList types=brandEle.getChildNodes();
            for (int j = 0; j < types.getLength(); j++){
                Node type=types.item(j);
                if (type.getNodeType()==Node.ELEMENT_NODE){
                    Element typeEle=(Element) type;
                    String typeStr=typeEle.getAttribute("name");
                    System.out.println("手机"+brandStr+typeStr);
                }
            }
        }
    }

    /**
     * 第二章示例3
     * @param args
     */
    public void Examplethree(){
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        DocumentBuilder db= null;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
          e.printStackTrace();
        }
        Document doc = null;
        try {
            doc = db.parse("src/main/java/com.bdqn/dom/brandetwo.xml");
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
           e.printStackTrace();
        }
        NodeList list=doc.getElementsByTagName("pubdate");
        Element pubDateElement=(Element) list.item(0);
        String pubDate=pubDateElement.getFirstChild().getNodeValue();
        System.out.println(pubDate);
    }
    /**
     *第二章示例6
     */
    public void ExampleSix(){
        //得到DOM解析器的工厂实列
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //获取解析器工厂
        try {
            //从DOM工厂获取DOM解析器
            DocumentBuilder db = dbf.newDocumentBuilder();
            //解析XML文档，得到一个Document，即DOM树
            doc= db.parse("src/main/java/com.bdqn/dom/brandetwo.xml");

        } catch (ParserConfigurationException e) {
            e.fillInStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
        //找到要删除的节点
        NodeList list=doc.getElementsByTagName("Brand");
        for (int i = 0; i < list.getLength(); i++){
            Element brandElement=(Element) list.item(i);
            String brandName=brandElement.getAttribute("name");
            //找到name属性值为SAMSUNG的节点，进行删除
            if(brandName.equals("SAMSUNG")){
                //调用父节点的removeChild方法删除该节点
                brandElement.getParentNode().removeChild(brandElement);
            }
        }
        //保存XML文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        try {
            Transformer transformer=transformerFactory.newTransformer();
            DOMSource domSource=new DOMSource(doc);
            //设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
            StreamResult result=new StreamResult(new FileOutputStream("src/main/java/com.bdqn/dom/brandetwo.xml"));
            transformer.transform(domSource,result);
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     *第二章示例5
     */
    public void Examplefive() {
        //得到DOM解析器的工厂实列
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //获取解析器工厂
        try {
            //从DOM工厂获取DOM解析器
            DocumentBuilder db = dbf.newDocumentBuilder();
            //解析XML文档，得到一个Document，即DOM树
            doc= db.parse("src/main/java/com.bdqn/dom/brandetwo.xml");

        } catch (ParserConfigurationException e) {
            e.fillInStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
        //找到修改的节点
        NodeList list=doc.getElementsByTagName("Brand");
        for (int i = 0; i < list.getLength(); i++){
            Element brandElement=(Element) list.item(i);
            String brandName=brandElement.getAttribute("name");
            //如果name属性值为三星，则进行修改
            if(brandName.equals("三星")){
                brandElement.setAttribute("name","SAMSUNG");//修改属性
            }
        }
        //保存XML文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        try {
            Transformer transformer=transformerFactory.newTransformer();
            DOMSource domSource=new DOMSource(doc);
            //设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
            StreamResult result=new StreamResult(new FileOutputStream("src/main/java/com.bdqn/dom/brandetwo.xml"));
            transformer.transform(domSource,result);
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 第二章示例4
     * @param args
     */
    public void Examplefour(){
        //得到DOM解析器的工厂实列
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //获取解析器工厂
        try {
            //从DOM工厂获取DOM解析器
            DocumentBuilder db = dbf.newDocumentBuilder();
            //解析XML文档，得到一个Document，即DOM树
            doc= db.parse("src/main/java/com.bdqn/dom/brandetwo.xml");

        } catch (ParserConfigurationException e) {
            e.fillInStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
       //创建Brand节点
        Element brandElement =doc.createElement("Brand");
        brandElement.setAttribute("name","三星");
        //创建Type节点
        Element typeElement =doc.createElement("Type");
        typeElement.setAttribute("name","NoteX");
         //添加父子关系
        brandElement.appendChild(typeElement);
        Element phoneElement =(Element) doc.getElementsByTagName("PhoneInfo").item(0);
        phoneElement.appendChild(brandElement);
         //保存XML文件
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        try {
            Transformer transformer=transformerFactory.newTransformer();
            DOMSource domSource=new DOMSource(doc);
            //设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
            StreamResult result=new StreamResult(new FileOutputStream("src/main/java/com.bdqn/dom/brandetwo.xml"));
            transformer.transform(domSource,result);
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        XMLParse xmlParse=new XMLParse();
        //xmlParse.getDocument();
        //xmlParse.showInfo();
        //xmlParse.Examplethree();
        //xmlParse.Examplefour();
        //xmlParse.Examplefive();
        //xmlParse.ExampleSix();
    }
}
